package team.archai.nexus.boot.auth.model;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import team.archai.nexus.boot.tool.DesUtil;
import team.archai.nexus.boot.tool.Tool;


/**
 * @description: 认证成功返回信息
 * @author: lishibin
 * @create: 2020-06-27 13:55
 **/
@Getter
@Setter
@Builder
public class AuthenticatedInfo {

    /**
     * @program: AuthenticatedInfo
     * @description: 用户名称
     * @author: lishibin
     * @create: 15:18
     **/
    private String subject;

    /**
     * @program: AuthenticatedInfo
     * @description: 用户密码
     * @author: lishibin
     * @create: 15:18
     **/
    @JsonIgnore
    private Object credential;

    /**
     * @program: AuthenticatedInfo
     * @description: 授权成功的token
     * @author: lishibin
     * @create: 15:18
     **/
    private String token;

    /**
     * @program: AuthenticatedInfo
     * @description: 过期时间
     * @author: lishibin
     * @create: 15:18
     **/
    private Long expire;

    /**
     * @program: AuthenticatedInfo
     * @description: 随机key
     * @author: lishibin
     * @create: 11:23
     **/
    private String keyId;

    /**
     * @program: AuthenticatedInfo
     * @description: 加密的扩展json
     * @author: lishibin
     * @create: 11:23
     **/
    private String additionalJson;

    /**
     * @program: AuthenticatedInfo
     * @description: 解密扩展json
     * @author: lishibin
     * @create: 11:27
     **/
    public String decodeAdditionalJson() {
        if (Tool.isEmpty(this.keyId) || Tool.isEmpty(this.additionalJson)) {
            return null;
        }
        return DesUtil.decrypt(this.keyId, this.additionalJson);
    }

    /**
     * 加密 additionalJson
     */
    public AuthenticatedInfo encodeAdditionalJson() {
        if (Tool.isEmpty(this.keyId) || Tool.isEmpty(this.additionalJson)) {
            return this;
        }
        this.additionalJson = DesUtil.encrypt(this.keyId, this.additionalJson);
        return this;
    }

    /**
     * @program: AuthenticatedInfo
     * @description: 通过jwt 初始化一些数据
     * @author: lishibin
     * @create: 13:39
     **/
    public void initByJWT(DecodedJWT decodedJwt, AuthenticatedInfo authInfo) {
        String encodeKeyId = decodedJwt.getKeyId();
        authInfo.setCredential(DesUtil.decrypt(encodeKeyId, decodedJwt.getClaim("credential").asString()));
        authInfo.setSubject(decodedJwt.getSubject());
        authInfo.setAdditionalJson(decodedJwt.getClaim(decodedJwt.getSubject()).asString());
        authInfo.setKeyId(encodeKeyId);
    }

}
